package org.seanye.com.junitrunnerui.junit;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import junit.framework.TestCase;

/**
 * 
 * @author seany1
 * 
 */
public class Junit3Test {
	private static final String TEST_NAME_PATTERN = "^test[\\w_\\d]+";
	private Class<TestCase> caseKlass;
	private List<Method> testMethods;

	public Junit3Test(Class<TestCase> caseKlass) {
		super();
		this.caseKlass = caseKlass;
		findTests(caseKlass);
	}

	/**
	 * Find tests from class
	 * 
	 * @param caseKlass
	 */
	private void findTests(Class<TestCase> caseKlass) {
		Method[] methods = caseKlass.getMethods();
		testMethods = new ArrayList<Method>(methods.length);
		for (Method method : methods) {
			// public void testXXX() with no arguments.
			if (method.getModifiers() == Modifier.PUBLIC) {
				if (method.getReturnType() == Void.TYPE) {
					if (method.getParameterTypes() == null
							|| method.getParameterTypes().length == 0) {
						String name = method.getName();
						if (name.matches(TEST_NAME_PATTERN)) {
							testMethods.add(method);
						}
					}
				}
			}
		}
	}

	public Class<TestCase> getCaseKlass() {
		return caseKlass;
	}

	public void setCaseKlass(Class<TestCase> caseKlass) {
		this.caseKlass = caseKlass;
	}

	public List<Method> getTestMethods() {
		return testMethods;
	}

	public void setTestMethods(List<Method> testMethods) {
		this.testMethods = testMethods;
	}

	public boolean isValid() {
		return this.testMethods != null && this.testMethods.size() > 0;
	}
}
